package com.china08.yxyapi.api.manage.tec.teaching.zujuan.previewpaper;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteStreams;
import com.google.gson.Gson;

import io.swagger.annotations.ApiOperation;

/**
 * 组卷图片代理服务器
 * 
 * 
 */
@CrossOrigin
@RestController
public class ZujuanPaperProxyController extends YxyApiBaseController {

    Pattern callbackPattern = Pattern.compile("[a-zA-Z_$][0-9a-zA-Z_$]*");

    @ApiOperation(value = "图片代理服务器")
    @RequestMapping(value = "/api_yw/comm/proxy", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void process(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        URL url = new URL(extractUrl(req.getParameter("url")));
        String callback = req.getParameter("callback");

        URLConnection connection = url.openConnection();
        InputStream data = connection.getInputStream();
        String contentType = connection.getContentType();

        if (callback == null) {
            resp.setContentType(contentType);
            ByteStreams.copy(data, resp.getOutputStream());
        } else {
            if (!callbackPattern.matcher(callback).matches()) { throw new ServletException("Invalid callback name"); }
            resp.setContentType("application/javascript");
            Writer out = new OutputStreamWriter(resp.getOutputStream(), "UTF-8") {
                @Override
                public void close() throws IOException {
                    // Base64 stream will try to close before jsonp suffix is
                    // added.
                };
            };
            String dataUri = new Gson().toJson("data:" + contentType + ";base64,");
            out.write(callback + "(" + dataUri.substring(0, dataUri.length() - 1));
            OutputStream base64Stream = BaseEncoding.base64().encodingStream(out);
            ByteStreams.copy(data, base64Stream);
            base64Stream.close();
            out.write("\");");
            out.flush();
        }
    }

    public String extractUrl(String url) {
        return url.replaceAll("url=", "").replaceAll("%3A", ":").replaceAll("%2F", "/");
    }

}
